var mRequest = require('./OrderDetailsService.js');
var wxPayUtils = require('../../utils/wxPayUtils.js');
const constant = require('../../utils/constant.js');
const utilService = require('../../utils/utilService.js');
let noti = require('../../utils/WxNotificationCenter.js');
let app = getApp()
// pages/orderDetails/OrderDetails.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressData: null,      // 地址
    inputValue: '',              // input快递单号值
    defaultInfo: '',             // 备注信息
    isMaill: false,              // false是买家  true是卖家
    isUpdataAdress: true,       // 修改地址是否显示
    orderId: '',                  // 订单ID
    byShareMsg: '我发现了一个闲置物品的好平台【趣闲】，特意分享给你！',
    saleShareMsg: '我发现了一个闲置物品的好平台【趣闲】，特意分享给你！',
    isOrderDetailsVisible: false,// 快递单号、支付果冻、支付用户是否显示
    isBottomVisible: false,      // 底部所有订单信息是否显示
    isStatusListVisible: true,   // 顶部订单状态是否显示
    isShotVisible: false,        // 支付是否显示
    isPaidVisible: false,        // 等待发货是否显示
    isCollectVisible: false,     // 去感谢 或确认收货 或竞拍中 是否显示
    isOrderCancleVisible: false, //订单取消是否显示
    btnText: '去感谢',           // 去感谢 或确认收货文案
    handleStatus: '待处理',      // 处理状态
    orderData: {},               // 订单详情数据
    saleTypeId: 1,//订单类型
    groupbuyId:"",
    groupbuyUserId:"",
    orderDetailsDatas: [
      {
        url: '../../images/my-tksh.png',
        isExpire: true,
        name: '已拍下'
      },
      {
        url: '../../images/my-tksh.png',
        isExpire: false,
        name: '已付款'
      },
      {
        url: '../../images/my-tksh.png',
        isExpire: false,
        name: '已发货'
      },
      {
        url: '../../images/my-tksh.png',
        isExpire: false,
        name: '已收货'
      }
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('接收到的数据' + JSON.stringify(options))
    // 获取要了popuwindow实例
    this.commitpopuWindow = this.selectComponent("#commitpopuWindow");
    //授权
    this.authAlert = this.selectComponent("#authAlert");
    this.authAlert.bindCatch()

    this.setData({
      orderId: options.order_id
    })
  },

  initRequestData: function () {
    // 订单详情接口请求
    this.requestOrder();
  },

  /**
   * 收货地址修改
   */
  updataAdressClick: function () {
    wx.navigateTo({
      url: '/pages/addProduct/myAddress/myAddres',
    })
  },

  requestOrder: function () {
    var that = this
    var param = {
      userId: app.globalData.userId,
      orderId: this.data.orderId
    };
    mRequest.getOrderDetailsData(param,
      function (success) {
        console.log('订单详情成功')
        that.showOrderData(success)
      })
  },

  /**
   * 申请寄件/填写快递单号/确认收货/去感谢 点击事件
   */
  clickAll: function () {
    if (this.data.btnText == '已完成') { // 订单已完成不让点击
      return
    }
    if (this.data.orderData.status == 1) {
      if (this.data.orderData.mailStatus == 0) {
        // 申请寄件
        console.log('申请寄件')
        let data = JSON.stringify(this.data.orderData)
        wx.navigateTo({
          url: "/pages/publishExpress/publishExpress?data=" + data
        })
      } else {
        // 填写快递单号
        this.commitpopuWindow.show();
      }
    } else if (this.data.orderData.status == 2) {
      if (this.data.orderData.userId == getApp().globalData.userId) {
        // 买家确认收货
        this.showCoolectGoods()
      }
    } else if (this.data.orderData.status == 3) {
      let orderObject = {
        goodsId: this.data.orderData.goodsId,
        id: this.data.orderId,
        goodsName: this.data.orderData.goodsName,
        sellerUserId: this.data.orderData.sellerUserId
      }
      let data = JSON.stringify(orderObject)
      // 去感谢
      wx.navigateTo({
        url: "/mineSubs/pages/getFlowers/uploadVideo/uploadVideo?order=" + data
      })
    }
  },

  /**
   * 确认收货
   */
  showCoolectGoods: function () {
    let that = this
    let param = {
      orderId: this.data.orderId
    }

    mRequest.coolectGoods(param,
      function (data) {
        that.showTost('收货成功');
        // 订单详情接口请求 刷新状态
        that.requestOrder();
      })
  },

  /**
   * 查看详情
   */
  gotoDetailsClick: function () {
    if (this.data.saleTypeId == 2){
      wx.navigateTo({
        url: '/redPacket/pages/groupBuy/groupBuyGoodsDetail/groupBuyGoodsDetail?gBId=' + this.data.groupbuyId + "&gBUId=" + this.data.groupBuyUserId + "&goodsId=" + this.data.orderData.goodsId,
      })
    }else{
      wx.navigateTo({
        url: "/goods/pages/goodsDetails/goodsDetails?goods_id=" + this.data.orderData.goodsId + '&goods_type='
        + this.data.saleTypeId
      })
    }
  },

  showOrderData: function (success) {
    //0：已拍下1：已付款2：已发货3：已完成，4竞拍中 5已取消）
    if (success) {
      if (success.userId != getApp().globalData.userId) {
        this.setData({
          isMaill: true,
        })
      } else {
        this.setData({
          isUpdataAdress: success.status == 0 ? false : true //已拍下显示收货地址
        })
      }
      this.setData({
        saleTypeId: success.saleTypeId,
        groupbuyId: success.groupbuyId,
        groupBuyUserId: success.groupBuyUserId,
      })
      if (success.status == 0) {
        this.upStutas(0)
        this.data.handleStatus = '已拍下'
        if (success.userId != getApp().globalData.userId) {
          this.data.isCollectVisible = true      // 等待对方付款是否显示
          this.data.btnText = '等待对方付款'
        } else {
          // 支付view
          this.data.isShotVisible = true
        }
      } else if (success.status == 1) {
        this.upStutas(1)
        this.data.handleStatus = '已付款'
        this.data.isBottomVisible = true         // 底部总View
        this.data.isOrderDetailsVisible = true   // 快递单号、支付果冻、支付用户是否显示
        this.data.isShotVisible = false          // 支付隐藏
        if (success.userId != getApp().globalData.userId) {
          this.data.isCollectVisible = true      // 申请寄件或添加快递单号是否显示
          // mailStatus 邮寄状态 0 没有 1 有
          if (success.mailStatus == 0) {
            this.data.btnText = '申请寄件'
          } else {
            this.data.btnText = '填写快递单号'
          }
        } else {
          // 等待发货是否显示
          this.data.isPaidVisible = true
        }

      } else if (success.status == 2) {
        this.upStutas(2)
        this.data.handleStatus = '已发货'
        this.data.isBottomVisible = true         // 底部总View
        this.data.isOrderDetailsVisible = true   // 快递单号、支付果冻、支付用户是否显示
        this.data.isCollectVisible = true        // 设置确认收货view的显示
        if (success.userId != getApp().globalData.userId) {
          this.data.btnText = '等待对方收货'
        } else {
          this.data.btnText = '确认收货'
        }

      } else if (success.status == 3) {
        this.data.handleStatus = '已完成'
        this.data.isBottomVisible = true        // 底部所有订单信息是否显示
        this.data.isCollectVisible = true       // 设置去感谢view的显示
        this.upStutas(3)
        if (success.userId != getApp().globalData.userId) {
          this.data.btnText = '已完成'
        } else {
          this.data.btnText = '去感谢'
        }


      } else if (success.status == 4) {
        this.data.isCollectVisible = true        // 设置竞拍中 view的显示
        this.data.isStatusListVisible = false    // 顶部状态栏
        this.data.btnText = '竞拍中'
        this.data.handleStatus = '竞拍中'

      } else if (success.status == 5) {
        this.data.handleStatus = '订单已取消'
        this.data.isStatusListVisible = false
        this.data.isOrderCancleVisible = true
      }

      this.setData({
        inputValue: success.trackCode,
        orderData: success,
        orderDetailsDatas: this.data.orderDetailsDatas,   // 更新订单状态
        handleStatus: this.data.handleStatus,             // 更新处理状态

        isOrderDetailsVisible: this.data.isOrderDetailsVisible,//快递单号、支付果冻、支付用户是否显示
        isBottomVisible: this.data.isBottomVisible,      //底部所有订单信息是否显示

        isShotVisible: this.data.isShotVisible,          // 更新view是否显示  和 文案
        isPaidVisible: this.data.isPaidVisible,
        isCollectVisible: this.data.isCollectVisible,
        isStatusListVisible: this.data.isStatusListVisible,
        isOrderCancleVisible: this.data.isOrderCancleVisible,
        btnText: this.data.btnText
      })
    }
  },

  /**
   * 输入快递单号
   */
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  /**
   * 填写备注信息
   */
  bindInfoInput: function (e) {
    this.setData({
      defaultInfo: e.detail.value
    })
  },

  /**
   * 确认发货
   */
  clickDeliverGoods: function () {
    this.commitpopuWindow.hide()
    let that = this
    let param = {
      orderId: this.data.orderId,
      trackCode: this.data.inputValue,
      memo: this.data.defaultInfo
    }

    if (this.data.inputValue) {
      mRequest.comfireSendGoods(param,
        function (data) {
          that.showTost('发货成功');
          that.requestOrder()
        })
    } else {
      that.showTost('请填写快递单号')
    }
  },

  showTost: function (str) {
    wx.showToast({
      title: str,
      icon: 'none',
      duration: 1000,
      mask: true
    })
  },

  /**
   * 更定顶部订单状态
   */
  upStutas: function (position) {
    if (position == 0) {
      this.data.orderDetailsDatas[position].isExpire = true
    } else {
      for (var i = 0; i <= position; i++) {
        this.data.orderDetailsDatas[i].isExpire = true
      }
    }
  },

  /**
   * 点击支付
   */
  payClick: function () {
    let that = this
    let params = {
      userId: app.globalData.userId,
      price: this.data.orderData.postage,
      orderId: this.data.orderId,
    }
    console.log("支付运费支出", params)
    mRequest.prePay(params,
      function (data) {
        console.log("支付运费prePay", data);
        wxPayUtils.pay(data,
          function (error, data) {
            if (error) {
              // if (error.errMsg == "requestPayment:fail cancel") {
              //   console.log('支付取消' + error)
              // } else {
                console.log('支付失败' + error)
                // 跳支付失败页面
                wx.navigateTo({
                  url: "/pages/common/paySuccess/paySuccess?result=0&goodsData=" + JSON.stringify(that.data.orderData) + "&orderId=" + that.data.orderId
                })
              // }
            } else {
              console.log('支付成功' + data)
              // 刷新订单状态
              that.requestOrder();
              // 跳支付成功页面
              wx.navigateTo({
                url: "/pages/common/paySuccess/paySuccess?result=1&goodsData=" + JSON.stringify(that.data.orderData) + "&orderId=" + that.data.orderId
              })
            }
          })
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function () {
    var that = this;
    app.loginPromise.then(() => {
      that.getShareMessage(9);
      that.initRequestData();
    });
  },

  /**
   * 点击授权
   */
  authSuccess() {
    this.getShareMessage(9);
    this.initRequestData();
  },

  onReady: function () {
    // 接收通知，刷新地址，修改订单（修改地址通知）
    let that = this
    noti.addNotification(noti.refreshAddress, that.refreshProductds, this)
  },

  /**
   * 修改地址（修改订单）
   */
  refreshProductds: function () {
    if (this.data.addressData && this.data.addressData.name) {
      let that = this
      let pramas = {
        orderId: this.data.orderId,
        userName: this.data.addressData.name,
        phone: this.data.addressData.phone,
        addressDesc: this.data.addressData.region + this.data.addressData.address,
        addressId: this.data.addressData.id
      }
      mRequest.upOrdetails(pramas,
        function (data) {
          // 订单详情接口请求
          that.requestOrder();
        })
    }
  },

  onUnload: function () {
    noti.removeNotification(noti.refreshAddress, this)
  },

  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        console.log("分享数据", data)
        if (self.data.orderData.userId != app.globalData.userId) {
          self.setData({
            saleShareMsg: data.title
          })
        } else {
          self.setData({
            byShareMsg: data.title
          })
        }
      },
      function (error) {
      }
    );
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var title = ''
    var path = "pages/home/home?userId=" + getApp().globalData.userId
    if (this.data.orderData.userId != app.globalData.userId) {
      title = this.data.saleShareMsg
    } else {
      title = this.data.byShareMsg
    }
    return {
      title: title,
      path: path,
      imageUrl: this.data.orderData.goodsUrl,
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  }
})